package dk.simonvogensen.itodo;

import android.app.ProgressDialog;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class GetDataFromServlet {

    private static ITodoActivity activity;

    private String cookie;
    HttpClient client;

    private String data;
    private int index;
    private int latestIndex;

    private Exception ex;
    private ProgressDialog dialog;

    public void execute(ITodoActivity activity, final Command command, final int index, final String cookie, final String email, final String passwd) {

        dialog = ProgressDialog.show(activity, "", "Loading. Please wait...", true);

        this.activity = activity;

        // allows non-"edt" thread to be re-inserted into the "edt" queue
        final Handler uiThreadCallback = new Handler();

        // performs rendering in the "edt" thread, after background operation is complete
        final Runnable runInUIThread = new Runnable() {
            public void run() {
                showInUI();
            }
        };

        new Thread() {
            @Override
            public void run() {
                doInBackgroundPost(command, index, cookie, email, passwd);
                uiThreadCallback.post(runInUIThread);
            }
        }.start();
    }

    private void doInBackgroundPost(Command command, int index, String cookie, String email, String passwd) {
        try {
            if(client == null) {
                client = new HttpClient();
            }
            if(cookie == null) {
                PostMethod method = new PostMethod("https://www.google.com/accounts/ClientLogin");
                method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

                NameValuePair accountType = new NameValuePair("accountType", "HOSTED_OR_GOOGLE");
                NameValuePair emailNVP = new NameValuePair("Email", email);
                NameValuePair passwdNVP = new NameValuePair("Passwd", passwd);
                NameValuePair service = new NameValuePair("service", "ah");
                NameValuePair source = new NameValuePair("source", "Itodo-Itodo-b217");
                method.setRequestBody(new NameValuePair[]{accountType, emailNVP, passwdNVP, service, source});

                client.executeMethod(method);
                String auth = method.getResponseBodyAsString().split(System.getProperty("line.separator"))[2].split("=")[1];
                method.releaseConnection();


                String url = "http://itodoo.appspot.com/itodo/android";
                method = new PostMethod("http://itodoo.appspot.com/_ah/login?auth=" + auth + "&continue=" + url);
                client.executeMethod(method);
                method.addRequestHeader("Content-Type","text/plain; charset=UTF-8");
                this.cookie = method.getResponseHeader("Set-Cookie").getValue();
                method.releaseConnection();
            } else {
                this.cookie = cookie;
            }

            GetMethod method = null;
            switch (command) {
                case LatestItem:
                    Log.d("ITODO", "latestitem");
                    method = new GetMethod("http://itodoo.appspot.com/itodo/android");
                    break;
                case PrevItem:
                    method = new GetMethod("http://itodoo.appspot.com/itodo/android?index="+index);
                    Log.d("ITODO", "prev "+index);
                    break;
                case NextItem:
                    method = new GetMethod("http://itodoo.appspot.com/itodo/android?index="+index);
                    Log.d("ITODO", "next "+index);
                    break;
            }
            method.addRequestHeader("Content-Type","text/html; charset=UTF-8");
            method.addRequestHeader("Set-Cookie", this.cookie);
            client.executeMethod(method);

            convertStreamToData(command, method.getResponseBodyAsStream());
            Log.d("ITODO", "data: "+data);
            Log.d("ITODO", "index: "+index);
            method.releaseConnection();
        } catch (Exception e) {
            Log.e("ITODO", e.getMessage(), e);
            ex = e;
        }
    }

    public void convertStreamToData(Command command, InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            index = Integer.parseInt(reader.readLine().trim());
            if(command == Command.LatestItem) latestIndex = index;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        data = sb.toString();
    }

    private void showInUI() {
        if (ex != null) {
            Toast.makeText(activity,
                    ex.getMessage() == null ? "Error" : "Error - " + ex.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
        activity.displayUserProfile(index, latestIndex, data, cookie);
        dialog.cancel();
    }
}